package com.yanqu.road.server.timer.union.cross;

import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.cross.CrossUnionReward;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UploadUnionRewardTask extends GeneralTask {

    private Logger logger = LogManager.getLogger(this.getClass().getName());

    @Override
    public void doRun() {

        try {
            Map<Long, CrossUnionReward> map = CrossUnionMgr.getUnionRewardMap();
            //待移除列表
            List<Long> toRemoveList = new ArrayList<>();

            //没有unionUid的，设置unionUid后重传；玩家退出商会后，再去邮件提取的商贸奖励、排行奖励，没有上传商会跨服
            //这边等玩家重新加入商会后，重新上传
            List<CrossUnionReward> toReUploadList = new ArrayList<>();

            long currentSecond = DateHelper.getCurrentTime() / 1000;

            List<CrossUnionReward> list = new ArrayList<>(map.values());
            for (CrossUnionReward reward : list) {
                if (reward.getSync()== 0 && currentSecond - reward.getAddTime() > 3 * DateHelper.DAY_SECONDS) { //三天还没成功就说明是异常数据,不同步了
                    reward.setSync(2);
                }else {
                    if (!reward.isDirty() && reward.getSync() > 0) {
                        //已同步，入库 的移除内存
                        toRemoveList.add(reward.getRecordId());
                    } else if (StringUtils.isNullOrEmpty(reward.getUnionUid()) && reward.getSync() == 0) {
                        //unionUid 为空的  且未同步成功的
                        toReUploadList.add(reward);
                    }
                }
            }

            for (Long recordId : toRemoveList) {
                map.remove(recordId);
            }

            int i = 0;
            CrossUnionProto.CrossUnionUploadRewardReqMsg.Builder msg = null;
            int size = toReUploadList.size();
            for (int k = 0; k < size; k++) {
                if(i == 0){
                    msg = CrossUnionProto.CrossUnionUploadRewardReqMsg.newBuilder();
                }

                CrossUnionReward reward = toReUploadList.get(k);

                UserInfo userInfo = UserMgr.getUserInfo(reward.getUserId());

                if(userInfo != null && !StringUtils.isNullOrEmpty(userInfo.getUnionUid())){
                    reward.setUnionUid(userInfo.getUnionUid());
                    i++;
                    CrossUnionProto.CrossUnionRewardTemp.Builder builder = CrossUnionProto.CrossUnionRewardTemp.newBuilder();
                    builder.setRecordId(reward.getRecordId());
                    builder.setUnionUid(reward.getUnionUid());
                    builder.setReward(reward.getReward());
                    builder.setUserId(reward.getUserId());
                    builder.setType(reward.getType());
                    builder.setSon(reward.getSon());
                    msg.addReward(builder);
                    logger.info("UploadUnionRewardTask re upload play {} record {}, reward {}, unionUid {}", userInfo.getUserId(), reward.getRecordId(), reward.getReward(), reward.getUnionUid());
                }
                if(i == 100 || k == size - 1){
                    GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_UPLOAD_REWARD, msg));
                    i = 0;
                }
            }

        }catch (Exception e){
            logger.error("UploadUnionRewardTask error", e);
        }





    }
}
